#pragma once

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>

using namespace std;
typedef struct tagTcNode
{
	int m_nodeId;
	string m_nodeName;
	struct tagTcNode* pNext;
}TcNode,*P_TcNode,**DP_TcNode;

// 由于是单向链表，不能通过下一个结点找到上一个结点
// 所以上一个结点的地址需要暂存一下
bool initList(DP_TcNode pHeader,int nSize)
{
	bool bIsSuccess = true;
	P_TcNode pCurrent;
	for (int nIndex = 0; nIndex < nSize; nIndex++)
	{
		P_TcNode sigleNode = new TcNode();
		if (NULL == sigleNode)
		{
			bIsSuccess = false;
			break;
		}
		char buff[10];
		string strTag = "test";
		string strTmpName = itoa(nIndex,buff,10);


		sigleNode->m_nodeId = nIndex;
		sigleNode->m_nodeName = strTag + strTmpName;
		sigleNode->pNext = NULL;

		if (0 == nIndex)
		{
			*pHeader = sigleNode;
			pCurrent = *pHeader;  // 指向链表头
		}
		else
		{
			// 是否能够保证连续存储？
			//(pHeader+nIndex)->pNext = sigleNode;
			pCurrent->pNext = sigleNode;
			pCurrent = pCurrent->pNext;
		}
	}

	return bIsSuccess;
}

void showList(P_TcNode pHeader)
{
	if (NULL == pHeader)
	{
		return;
	}
	P_TcNode pCurrent;
	pCurrent = pHeader;
	while(NULL != pCurrent)
	{
		printf("show node id : %d ",pCurrent->m_nodeId);
		printf("show node name : %s\n",pCurrent->m_nodeName.c_str());
		pCurrent = pCurrent->pNext;
	}
}

int count(P_TcNode pHeader)
{
	int nCount = 0;
	if (NULL == pHeader)
	{
		return nCount;
	}
	P_TcNode pCurrent;
	pCurrent = pHeader;
	while(NULL != pCurrent)
	{
		nCount++;
		pCurrent = pCurrent->pNext;
	}

	return nCount;
}

bool appendNewOne(P_TcNode pHeader)
{
	bool bIsSuccess = true;
	P_TcNode sigleNode = new TcNode();
	if (NULL == sigleNode)
	{
		bIsSuccess = false;
		return bIsSuccess;
	}

	int nSize = count(pHeader);
	char buff[10];
	string strTag = "test add";
	string strTmpName = itoa(nSize,buff,10);


	sigleNode->m_nodeId = nSize;
	sigleNode->m_nodeName = strTag + strTmpName;
	sigleNode->pNext = NULL;

	P_TcNode pCurrent;
	pCurrent = pHeader;
	while (NULL != pCurrent)
	{
		if(NULL == pCurrent->pNext)
		{
			pCurrent->pNext = sigleNode;
			bIsSuccess = true;
			break;
		}

		pCurrent = pCurrent->pNext;
	}

	return bIsSuccess;
}

P_TcNode at(P_TcNode pHeader,int nIndex)
{
	//P_TcNode temp = NULL;
	P_TcNode pCurrent = pHeader;
	int nSize = count(pHeader);
	for (int nPos = 0; nPos < nSize; nPos++)
	{
		if (pCurrent == NULL)
		{
			break;
		}
		if (nPos == nIndex)
		{
			break;
		}
		pCurrent = pCurrent->pNext;
	}

	return pCurrent;
}

bool insert(P_TcNode pHeader,P_TcNode pNode,int nIndex)
{
	bool bIsSuccess = false;
	P_TcNode pCurrent = pHeader;

	P_TcNode pOldRe = at(pHeader,nIndex-1);
	P_TcNode pOldNode = at(pHeader,nIndex);

	pOldRe->pNext = pNode;
	pNode->pNext = pOldNode;

	return true;
}